package com.example.demo34;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;

/**
 * 提高代码的可读性
 */
public class IdGeneratorRef1 {

  private static final Logger logger = LoggerFactory.getLogger(IdGeneratorRef1.class);

  public String generate() {
    String id = "";
    try {
      String hostName = getHostnameFromLastHost();
      String randStr = genRandomAlphameric();
      long curTimeMillis = System.currentTimeMillis();
      id = String.format("%s-%d-%s", hostName, curTimeMillis, randStr);
    } catch (UnknownHostException e) {
      logger.warn("Failed to get the host name.", e);
    }

    return id;
  }

  private String getHostnameFromLastHost() throws UnknownHostException {
    String hostName = InetAddress.getLocalHost().getHostName();
    String[] tokens = hostName.split("\\.");
    if (tokens.length > 0) {
      hostName = tokens[tokens.length - 1];
    }
    return hostName;
  }

  private String genRandomAlphameric() {
    int RandomAlphamericCount = 8;
    char[] randomChars = new char[RandomAlphamericCount];
    int count = 0;
    Random random = new Random();
    while (count < RandomAlphamericCount) {
      int randomAscii = random.nextInt(122);
      boolean isDigit = randomAscii >= '0' && randomAscii <= '9';
      boolean isLowerCase = randomAscii >= 'a' && randomAscii <= 'z';
      boolean isUpperCase = randomAscii >= 'A' && randomAscii <= 'Z';
      if (isDigit || isLowerCase || isUpperCase) {
        randomChars[count] = (char)randomAscii;
        count++;
      }
    }
    return new String(randomChars);
  }
}

/*
 * 一般性的CheckList
 * 1、目录、模块、结构 x
 * 2、思想、原则、设计 
 * 3、可读、复用、扩展、易测试
 * 
 * 功能和非拱了的CheckList
 * 1、功能、异常、日志
 * 2、性能、安全、并发、易用
 * 
 * 问题：
 * 1、面向接口编程
 * 2、扩展性不好：
 * 3、可读性不好：a.没有注释；b.存在魔数、while内部获取字符的代码冗余，可以简化
 * 4、易测试：包含时间、host、随机数等未决行为，代码可测试性不好
 * 5、异常：异常内部处理没有抛到外层
 * 6、日志：
 * 7、性能：循环存在冗余计算，可以优化
 * 8、
 */